package com.jianyun.jyzs.http;


import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.util.Log;


import com.jianyun.jyzs.R;
import com.jianyun.jyzs.bean.User;
import com.jianyun.jyzs.dao.UserDao;
import com.jianyun.jyzs.fragment.ContactFragment;
import com.jianyun.jyzs.utils.EmptyHandle;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.SysConstant2;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 消息
 *
 * @author
 */
public class ContactModuleFmAsyncTaskGet extends AsyncTask<Object, Integer, String> {

    // 可变长的输入参数，与AsyncTask.exucute()对应
    public ContactModuleFmAsyncTaskGet(OnRefreshSuncessLisener onRefresh) {
        this.onRefreshSuncessLiseners=onRefresh;
        if (onRefreshSuncessLiseners==null){
            Log.i("test","1为空");
        }else {
            Log.i("test","1不为空");
        }
    }

    // 可变长的输入参数，与AsyncTask.exucute()对应
    public ContactModuleFmAsyncTaskGet(ContactFragment fm) {
    }

    public ContactModuleFmAsyncTaskGet() {
    }
    @Override
    protected String doInBackground(Object... params) {
        ContactFragment fm = (ContactFragment) params[0];
        try {
            HttpClient client = new DefaultHttpClient(); // 自己去初始化，通常会自己写一个DefaultHttpClient
            // 为Post设置一些头信息
            HttpPost post = new HttpPost(String.valueOf(params[1]));
            if (params[2] instanceof MultipartEntity) {
                post.setEntity((MultipartEntity) params[2]);
            } else if (params[2] instanceof List) {
                post.setEntity(new UrlEncodedFormEntity((List<NameValuePair>) params[2], HTTP.UTF_8));
            }
            // 请求超时
            client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
            // 读取超时
            client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);

            HttpResponse response = client.execute(post);
           /* 若状态码为200 ok */
            if (response.getStatusLine().getStatusCode() == 200) {
                /* 读返回数据 */
                String json = EntityUtils.toString(response.getEntity());
                try {
                    JSONObject object = new JSONObject(json);
                    if (object.getBoolean("result")) {//正常返回

                        if (object.getInt("pageIndex") < object.getInt("pageCnt")) {
                            ContactModuleFmAsyncTaskGet atfu = new ContactModuleFmAsyncTaskGet(this.onRefreshSuncessLiseners);
                            List<NameValuePair> paramsV = new ArrayList<NameValuePair>();
                            paramsV.add(new BasicNameValuePair("method", fm.act.getString(R.string.http_url_contact_method)));
//                            paramsV.add(new BasicNameValuePair("enterpriseCode", fm.enterpriseCode));
//                            paramsV.add(new BasicNameValuePair("id", fm.userId));
                            paramsV.add(new BasicNameValuePair("pageIndex", (object.getInt("pageIndex") + 1) + ""));
                            atfu.execute(fm, LoginCache.getInstance().getLoginCache().getErpHttpUrl() + fm.act.getResources().getString(R.string.http_url_common), paramsV);
                        }
                        List<User> users = object2Users(object,"");
                        UserDao udao = new UserDao(fm.getActivity());
                        if (object.getInt("pageIndex") == 1) {
//                            fm.contactList.clear();
//                            udao.deleteAllContact(fm.enterpriseCode, fm.userId);
                        }
                        if (users != null) {
                            for (User user : users) {
//                                user.setUserId(fm.userId);
//                                user.setEnterpriseCode(fm.enterpriseCode);
//									new UserDao(act).deleteOneContact(user.getEnterpriseCode(), user.getUserId(),user.getServerUserId());
                                udao.insert(user);//存库
//								if (Character.isDigit(user.getNameZh().charAt(0))) {
//									user.setHeader("#");
//								} else {
//									user.setHeader(CommonUtils.getFirstChar(user.getNameZh()));
//									char header = user.getHeader().toLowerCase().charAt(0);
//									if (header < 'a' || header > 'z') {
//										user.setHeader("#");
//									}
//								}
//					        	fm.contactList.add(user);
                            }
                        }
                        if (object.getInt("pageIndex") < object.getInt("pageCnt")) {
                        } else {
//						if(fm.tv_selContacts.getText().toString().equals(fm.getString(R.string.text_allContact))){
                            fm.act.isCommonContact = false;
//					        // 对list进行排序
//					        Collections.sort(fm.contactList, fm.new PinyinComparator() {});
//					        
//							fm.adapter = new ContactModuleFmAdapter(fm.act, R.layout.item_contact_list,fm.contactList);
//							fm.listView.setAdapter(fm.adapter);
//							fm.processContactList(users);
                            //
//		    		       if(fm.contactList.size() > 10){
//		    		    	   fm.tv_total.setText(String.valueOf(fm.contactList.size())+"位联系人");
//		    		       }else{
//		    		    	   fm.tv_total.setText("");
//		    		       }

//		        		}else{
//		        			fm.act.isCommonContact = true;
//		        			fm.tv_selContacts.setText(fm.getString(R.string.text_commonContact));
//		        			fm.adapter = new ContactModuleFmAdapter(fm.act,R.layout.item_contact_list,fm.users_temp);
//		        			fm.listView.setAdapter(fm.adapter);
//		        			fm.tv_total.setText(String.valueOf(count)+"位常用联系人");
//		        		}
                            ContactModuleFmAsyncTask fmTask = new ContactModuleFmAsyncTask();
                            fmTask.execute(fm);
                            return fm.getActivity().getString(R.string.action_contacts_update);
                        }
                    } else {
//                        if (fm.dialog != null && fm.dialog.isShowing()) {
//                            fm.dialog.dismiss();
//                        }
                        return object.getString("message");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                return "Error Response: " + response.getStatusLine().toString();
            }
        } catch (ClientProtocolException e) {
            return e.getMessage() == null ? "请求异常!" : e.getMessage().toString();
        } catch (IOException e) {
            return e.getMessage() == null ? "请求异常!" : e.getMessage().toString();
        } catch (Exception e) {
            return e.getMessage() == null ? "请求异常!" : e.getMessage().toString();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
    }
    /**
     * 在doInBackground 执行完成后，onPostExecute方法将被UI thread调用，后台的计算结果将通过该方法传递到UI thread.
     */
    @Override
    protected void onPostExecute(String fm) {

        if (null!=fm){

        }
        try {
            if (fm != null) {
                onRefreshSuncessLiseners.dissMiss();
//			   fm.getContactList();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onCancelled() {
    }

    /**
     * 该方法将在执行实际的后台操作前被UI thread调用。这个方法只是做一些准备工作，如在界面上显示一个进度条。
     */
    @Override
    protected void onPreExecute() {
    }

    public interface OnRefreshSuncessLisener {
        void dissMiss();
    }

    private OnRefreshSuncessLisener onRefreshSuncessLiseners;

//    public void setOnRefreshSuncessLisener(OnRefreshSuncessLisener onRefreshSuncessLisener) {
//        this.onRefreshSuncessLiseners = onRefreshSuncessLisener;
//    }

    /*
     * object转通讯录
     * object
     * userId 当前登录用户的serverUserId
     */
    public static List<User> object2Users(JSONObject object, String userId) throws Exception {
        List<User> users = new ArrayList<User>();
        User user = null;
        JSONObject obj = null;
        JSONArray userList = object.getJSONArray("list");//获取JSONArray
        for (int i = 0; i < userList.length(); i++) {//遍历JSONArray
            obj = userList.getJSONObject(i);
            user = new User();
            user.setServerUserId(obj.getString("id")); // 用户ID
            user.setName(obj.getString("userName")); // 账号
            user.setNameZh(obj.getString("name")); // 用户名称
            user.setEmail(obj.getString("email")); // 邮箱
            user.setPhoneNum(obj.getString("phoneNum"));//手机号
            user.setCompany(obj.getString("company"));//所在单位
            user.setDepartment(obj.getString("department"));//所在部门
            user.setSex(obj.getString("sex"));//性别
            user.setServerIconPath(obj.getString("iconPaths")); // 头像URL
            user.setUserType(SysConstant2.YES); // 用户类型,0:登录用户;1:朋友
            user.setUserId(userId);
            user.setOrderRank(obj.getString("OrderRank"));//序列号
            user.setUnitId(obj.getString("unitId"));
            try {
                user.setIsCommonContact(EmptyHandle.handleInt(obj.get("isContact")));
            } catch (Exception e) {
                e.printStackTrace();
            }
            users.add(user);
        }
        return users;
    }
}  